package it.orma.iridehr.validators;

import java.util.Collection;
import java.util.Collections;

import it.orma.iridehr.controllers.ricerca.LingueConosciuteForm;
import it.orma.iridehr.entities.AltraLingua;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.stereotype.Component;

@Component
public class LingueConosciuteFormValidator {
	public void validate(final LingueConosciuteForm form, ValidationContext context) {
		MessageContext messages = context.getMessageContext();
		if (form.isValidateLingueConosciute()){
			if (StringUtils.isEmpty(form.getLingueConosciute().getLinguaMadre1())){
				messages.addMessage(new MessageBuilder().error().source("lingueConosciute.linguaMadre1")
						.code("error.campo.obbligatorio").build());
				
			}
		}
		if (form.isValidateAltraLingua()){
			if (StringUtils.isEmpty(form.getAltraLingua().getLingua())){
				messages.addMessage(new MessageBuilder().error().source("altraLingua.lingua")
						.code("error.campo.obbligatorio").build());
			}
			if (StringUtils.isEmpty(form.getAltraLingua().getCapacita())){
				messages.addMessage(new MessageBuilder().error().source("altraLingua.capacita")
						.code("error.campo.obbligatorio").build());
			}
			if (StringUtils.isEmpty(form.getAltraLingua().getLivello())){
				messages.addMessage(new MessageBuilder().error().source("altraLingua.livello")
						.code("error.campo.obbligatorio").build());
			}
			if (form.getLingueConosciute()!=null&&form.getLingueConosciute().getAltreLingue()!=null){
				@SuppressWarnings("unused")
				Collection<AltraLingua> results = CollectionUtils.select(form.getLingueConosciute().getAltreLingue(), new Predicate() {
					
					@Override
					public boolean evaluate(Object object) {
						AltraLingua altraLingua = (AltraLingua) object;
						EqualsBuilder eq = new EqualsBuilder();
						eq.append(altraLingua.getCapacita(), form.getAltraLingua().getCapacita());
						eq.append(altraLingua.getLingua(), form.getAltraLingua().getLingua());
						
						return eq.isEquals();
					}
				});
				if (results.size()>0){
					
						messages.addMessage(new MessageBuilder().error().source("altraLingua.lingua")
								.code("error.lingua.inserita").build());
				}
			}
			
			
		}
	}
}
